package com.example.messenger;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class ViewMessage extends Activity  {
	Messages mes = new Messages();
	String receiver="";
	String fromuser="";
	String datetime="";
	String message="";
	String VIEW2="";
	String status="";
	
	private static final String PHP_REC = "http://softeng.cs.uwosh.edu/students/cs342g4/receivemessage.php";
	
	int id=-1;
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_view_message);
		Intent intent = getIntent();


		mes = (Messages)intent.getSerializableExtra("message");
		try{
			status = intent.getStringExtra(VIEW2);
		}
		catch(Exception e){
			System.out.println("Not saved");
		}
		Button saveButton = (Button) findViewById(R.id.saveButton);
		Button deleteButton = (Button) findViewById(R.id.deleteButton);
		if (status.equals("Saved")){
			saveButton.setVisibility(View.GONE);
		}
		receiver= mes.getReciever();
		fromuser = mes.getSender();
		datetime = mes.getTime();
		message = mes.getMessage();
		populateView(mes);
		
		
		saveButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v){
				save(v);
			}
		});
		
		
		deleteButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v){
				if (status.equals("Saved")){
					MessengerDataSource mds2 = new MessengerDataSource(ViewMessage.this);
					
					mds2.open();
					
					try {
						mds2.deleteMessage(mes.getSender(),mes.getTime());
					} catch (Exception e) {
						System.out.println("Delete failed");
						e.printStackTrace();
					}
					
					mds2.close();
					
					Intent myIntent = new Intent(ViewMessage.this, MainActivity.class);
					startActivityForResult(myIntent, 0);
					finish();
					
				}
				else{
					delete(v);
				}
				
			}
		});
	}
	
	private void populateView(Messages mes){
		TextView timV = (TextView)findViewById(R.id.timeView);
		timV.setText(mes.getTime());
		TextView senV = (TextView)findViewById(R.id.sendView);
		senV.setText(mes.getSender());
		TextView recV = (TextView)findViewById(R.id.recieveView);
		recV.setText(mes.getReciever());
		TextView mesV = (TextView)findViewById(R.id.fullMessageView);
		mesV.setText(mes.getMessage());
	}
	
	//save message to sqlite and call receive message
	public void save(View view){
		MessengerDataSource mds2 = new MessengerDataSource(ViewMessage.this);
		
		mds2.open();
		
		try {
			mds2.insertMessage(receiver, fromuser, message, datetime);
		} catch (Exception e) {
			System.out.println("Insert Failed");
			e.printStackTrace();
		}
		
		mds2.close();
		
		//on post
		new ReceiveMessageTask().execute();
	}
	//dont save message and call receive message
	public void delete(View view){
		new ReceiveMessageTask().execute();
	}
	
	
	
	public class ReceiveMessageTask extends AsyncTask<Void, Void, Boolean> {
		@Override
		protected Boolean doInBackground(Void... params) {
			// TODO: attempt authentication against a network service.
			Boolean success = false;
			ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
			
			if(networkInfo != null && networkInfo.isConnected())
			{
				ArrayList<NameValuePair> n = new ArrayList<NameValuePair>(1);
				n.add(new BasicNameValuePair("receiver", receiver));
				n.add(new BasicNameValuePair("fromuser", fromuser));
				n.add(new BasicNameValuePair("datetime", datetime));
				
				
				HttpClient httpClient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(PHP_REC);
				
				try
				{
					httppost.setEntity(new UrlEncodedFormEntity(n));
					ResponseHandler<String> respondHandler = new BasicResponseHandler();
					String response = httpClient.execute(httppost, respondHandler);
					success = true;
				}
				catch(Exception e){
					System.out.println("Receive Failed");
				}
			}
			
			return success;
		}
		
		@Override
		protected void onPostExecute(Boolean whatever) {
			if(whatever){
				Intent myIntent = new Intent(ViewMessage.this, MainActivity.class);
				startActivityForResult(myIntent, 0);
				finish();
			}
		}
	}
	
	
}
